<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
        <title>Document</title>
        <style>
            #div1{width: 100px; height: 100px; background-color: red; position: absolute;}
        </style>
        <script>
            /* 
                拖拽：（拖拽的三剑客）  伪代码(代码草稿)
                    mousedown
                        记录鼠标按下位置和被拖拽物体相对距离
                        var offsetX = e.clientX - node.offsetLeft;
                        var offsetY = e.clientY - node.offsetTop;
                    mousemove
                        一致保持，相对距离
                        node.style.left = e.clientX - offsetX + 'px';
                        node.style.top = e.clientY - offsetY + 'px';
                    mouseup
                        取消拖拽
             */
             window.onload = function(){
                 var oDiv = document.getElementById("div1");
                 oDiv.onmousedown = function(ev){
                     var e = ev || window.event;
                     //记录鼠标和被拖拽物体相对位置
                     var offsetX = e.clientX - oDiv.offsetLeft;
                     var offsetY = e.clientY - oDiv.offsetTop;

                    //被拖拽物体保持相对距离和鼠标移动
                     document.onmousemove = function(ev){
                         var e = ev || window.event;
                         oDiv.style.left = e.clientX - offsetX + 'px';
                         oDiv.style.top = e.clientY - offsetY + 'px';
                     }
                 }
                 //取消拖拽
                 document.onmouseup = function(){
                    document.onmousemove = null;
                 }
             }
        </script>
    </head>
    <body>
        <div id = 'div1'></div>
    </body>
</html>